using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Helpers
{
    public static class StringHelper
    {
        public static string FormatIfExists(string format, params object[] args)
        {
            if (Array.TrueForAll<object>(args, ObjectNotNull))
            {
                return SafeFormat(format, args);
            }
            else
            {
                return null;
            }
        }

        public static string SafeFormat(object input)
        {
            return SafeFormat("{0}", input);
        }

        public static string SafeFormat(string format, params object[] args)
        {
            if (String.IsNullOrEmpty(format))
            {
                return "";
            }
            else
            {
                if (format.Length > 0 && args.Length == 0)
                {
                    return HttpContext.Current.Server.HtmlEncode(format);
                }
                else
                {
                    string[] safeArgs = Array.ConvertAll<object, string>(args, HtmlEncode);
                    return string.Format(format, safeArgs);
                }
            }
        }

        private static bool ObjectNotNull(object obj)
        {
            if (obj is string)
            {
                return !string.IsNullOrEmpty(obj as string);
            }
            else
            {
                return (obj != null);
            }
        }

        private static string HtmlEncode(object obj)
        {
            if (obj != null)
            {
                return HttpContext.Current.Server.HtmlEncode(obj.ToString());
            }
            else
            {
                return "";
            }
        }
    }
}